﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Autodesk.AutoCAD.Interop;
using Autodesk.AutoCAD.Interop.Common;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Windows;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Colors;
using System.Drawing;
using System.Drawing.Imaging;
using ZXing;
using ZXing.QrCode;
using ZXing.Common;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using System.Reflection;
using System.ComponentModel;


namespace cadbom
{
    class SetObject
    {
        String baigeBlockCadHandleId = "";
        public void GetTableTextHeight()
        {

            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            // 提示用户选择一个表格
            PromptEntityOptions peo = new PromptEntityOptions("\n选择一个表格: ");
            peo.SetRejectMessage("\n选择的对象不是表格，请重新选择。");
            peo.AddAllowedClass(typeof(Table), true);
            PromptEntityResult per = ed.GetEntity(peo);

            if (per.Status != PromptStatus.OK)
                return;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                // 打开表格对象
                Table table = tr.GetObject(per.ObjectId, OpenMode.ForRead) as Table;

                // 遍历表格的每一行和每一列
                for (int row = 0; row < table.Rows.Count; row++)
                {
                    for (int col = 0; col < table.Columns.Count; col++)
                    {
                        // 获取原单元格的TextStyleId
                        Cell cell = table.Cells[row, col];
                        // 获取单元格的文字样式
                        // 创建一个新的单元格样式
                       
                        // 输出文字高度
                        ed.WriteMessage("\n表格单元格({0}, {1})的文字高度为: {2}", row, col, cell.TextHeight);
                    }
                }

                tr.Commit();
            }
        }
        public void UpdateTableSelection(List<string[]> insertTableDatas)
        {
            try
            {
                int recSize = insertTableDatas.Count();//this.dataGridView1.Rows.Count;
                Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                Database db = doc.Database;
                Editor ed = doc.Editor;
                double dwgScale = db.Dimscale;
                DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument();
                // 输入要选择的表格句柄
                if (PromptStatus.OK == PromptStatus.OK)
                {
                    string handle = GValues.cadHandleId;// handleResult.StringResult;
                    using (Transaction tr = db.TransactionManager.StartTransaction())
                    {
                        //BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                        //BlockTableRecord modelSpace = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord;
                        ObjectId objectid = db.GetObjectId(false, new Handle(long.Parse(handle)), 0);
                        ObjectId[] ids = new ObjectId[] { objectid };
                        if (ids.Length > 0)
                        {
                            foreach (ObjectId id in ids)
                            {
                                Entity ent = id.GetObject(OpenMode.ForWrite) as Entity;
                                //Entity ent1 = tr.GetObject(id, OpenMode.ForRead) as Entity; 另外一种获取表格的方法
                                if (ent is Table)
                                {
                                    //表格头有2行
                                    Table table = ent as Table;
                                    Cell cell = table.Cells[1, 0];
                                    double textHeight = (double) cell.TextHeight;
                                    ObjectId textStyleId = (ObjectId)cell.TextStyleId;
                                    Autodesk.AutoCAD.Colors.Color color = cell.ContentColor;

                                    //解锁
                                    for (int row = 0; row < (table.Rows.Count - 2); row++)
                                    {

                                        table.Cells[row + 2, 0].State = CellStates.None;
                                        table.Cells[row + 2, 1].State = CellStates.None;
                                        table.Cells[row + 2, 2].State = CellStates.None;
                                        table.Cells[row + 2, 3].State = CellStates.None;
                                        table.Cells[row + 2, 4].State = CellStates.None;
                                    }
                                    if (recSize > (table.Rows.Count - 2))
                                    {
                                        int newRow = table.Rows.Count; // 添加到倒数第二行，最后一行为标题行
                                        table.InsertRows(newRow, table.Rows[0].Height, (recSize - (table.Rows.Count - 2))); // 在指定位置插入新行

                                    }
                                    if (recSize < ((table.Rows.Count - 2)))
                                    {
                                        int delRows = (table.Rows.Count - 2) - recSize;
                                        int atRow = table.Rows.Count - delRows; // 添加到倒数第二行，最后一行为标题行
                                        //table.DeleteRows(newRow, ( (table.Rows.Count - 2) - recSize));
                                        table.DeleteRows(atRow, delRows);
                                    }
                                    for (int row = 0; row <  (table.Rows.Count - 2); row++)
                                    {
                                        table.Cells[row + 2, 0].TextString = (row + 1).ToString();
                                        table.Cells[row + 2, 1].TextString = insertTableDatas[row][0];
                                        table.Cells[row + 2, 2].TextString = insertTableDatas[row][1];
                                        table.Cells[row + 2, 3].TextString = insertTableDatas[row][2];
                                        table.Cells[row + 2, 4].TextString = insertTableDatas[row][3];

                                        table.Cells[row + 2, 0].State = CellStates.ContentLocked;
                                        table.Cells[row + 2, 1].State = CellStates.ContentLocked;
                                        table.Cells[row + 2, 2].State = CellStates.ContentLocked;
                                        table.Cells[row + 2, 3].State = CellStates.ContentLocked;
                                        table.Cells[row + 2, 4].State = CellStates.ContentLocked;


                                        table.Cells[row + 2, 0].TextHeight = textHeight;
                                        table.Cells[row + 2, 1].TextHeight = textHeight;
                                        table.Cells[row + 2, 2].TextHeight = textHeight;
                                        table.Cells[row + 2, 3].TextHeight = textHeight;
                                        table.Cells[row + 2, 4].TextHeight = textHeight;

                                        table.Cells[row + 2, 0].TextStyleId = textStyleId;
                                        table.Cells[row + 2, 1].TextStyleId = textStyleId;
                                        table.Cells[row + 2, 2].TextStyleId = textStyleId;
                                        table.Cells[row + 2, 3].TextStyleId = textStyleId;
                                        table.Cells[row + 2, 4].TextStyleId = textStyleId;

                                        table.Cells[row + 2, 0].ContentColor = color;
                                        table.Cells[row + 2, 1].ContentColor = color;
                                        table.Cells[row + 2, 2].ContentColor = color;
                                        table.Cells[row + 2, 3].ContentColor = color;
                                        table.Cells[row + 2, 4].ContentColor = color;

                                        table.Cells[row + 2, 0].Alignment = CellAlignment.MiddleCenter;
                                        table.Cells[row + 2, 1].Alignment = CellAlignment.MiddleCenter;
                                        table.Cells[row + 2, 2].Alignment = CellAlignment.MiddleCenter;
                                        table.Cells[row + 2, 3].Alignment = CellAlignment.MiddleCenter;
                                        table.Cells[row + 2, 4].Alignment = CellAlignment.MiddleCenter;
                                    }
                                    //table.GenerateLayout();
                                }
                            }
                        }
                        tr.Commit();
                        docLock.Dispose();
                        doc.Editor.UpdateScreen();
                        doc.Editor.Regen();
                    }
                }
            }
            catch (System.Exception err)
            {

            }
        }
        public void InsertTableSelection(List<string[]> insertTableDatas)
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument();
            ObjectId tableObjectid;
            double dwgScale = db.Dimscale;

            // 获取当前视口的比例因子
            double currentViewportScale = 1.0;
            using (ViewTableRecord view = ed.GetCurrentView())
            {
                currentViewportScale = view.Height / view.Width;
            }
            // 定义原始表格的大小和位置
            double tableWidth = 200.0;  // 表格的宽度
            double tableHeight = 40.0;  // 表格的高度
            // 根据视口比例因子调整表格大小
            tableWidth *= currentViewportScale;
            tableHeight *= currentViewportScale;

            // 提示用户选择第一个角点
            // 获取点
            PromptPointOptions pointOptions = new PromptPointOptions("\n请点击位置插入表格");
            PromptPointResult pointResult = ed.GetPoint(pointOptions);
            if (pointResult.Status != PromptStatus.OK)
            {
                ed.WriteMessage("未选择表格插入点。\n");
                return;
            }

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                // 获取当前的图纸设置对象
                tableWidth *= dwgScale; //ds.Dimscale;
                tableHeight *= dwgScale;// ds.Dimscale;

                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                BlockTableRecord modelSpace = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

                int rows = insertTableDatas.Count();
                // 创建一个表格
                Table table = new Table();
                table.TableStyle = db.Tablestyle;
                //table.Position = new Point3d((firstPoint.X + secondPoint.X) / 2, (firstPoint.Y + secondPoint.Y) / 2, 0);  //更新插入方式0409
                //table.Position = new Point3d(0, 0, 0);
                // 确保使用世界坐标
                Point3d worldPoint = ConvertToWorldCoordinate(pointResult.Value, ed);

                table.Position = worldPoint;//20250907 //pointResult.Value; //更新插入方式0409
                table.SetSize(rows + 2, 5);
                table.SetRowHeight(tableHeight / (rows + 2));
                table.SetColumnWidth(tableWidth / 5);
                table.SetColumnWidth(0, (tableWidth / 5) / 2); //第一列缩小
                table.SetColumnWidth(1, (tableWidth / 5) / 1.5); //第一列缩小
                table.SetColumnWidth(2, (tableWidth / 5) + (tableWidth / 5) / 2); //第三列增加
                table.SetColumnWidth(3, (tableWidth / 5) + (tableWidth / 5) / 2); //第三列增加
                table.SetColumnWidth(4, (tableWidth / 5) / 1.5); //第一列缩小
                //RowType.DataRow
                table.SetTextHeight(2 * dwgScale, 4);
                table.SetTextHeight(2 * dwgScale, 2);
                table.SetTextHeight(2 * dwgScale, 1);

                // 将表格添加到模型空间
                modelSpace.AppendEntity(table);
                tr.AddNewlyCreatedDBObject(table, true);

                //表格名称
                table.Cells[0, 0].TextString = "物料BOM表格 (" + GValues.productCustCode + ")-" + GValues.account;
                table.Cells[0, 0].Alignment = CellAlignment.MiddleCenter;
                //表格头
                table.Cells[1, 0].TextString = "序号";
                table.Cells[1, 1].TextString = "类型";
                table.Cells[1, 2].TextString = "名称";
                table.Cells[1, 3].TextString = "规格/图号";
                table.Cells[1, 4].TextString = "用量";
                for (int row = 0; row < rows; row++)
                {
                    table.Cells[row + 2, 0].TextString = (row + 1).ToString();
                    table.Cells[row + 2, 1].TextString = insertTableDatas[row][0];
                    table.Cells[row + 2, 2].TextString = insertTableDatas[row][1];
                    table.Cells[row + 2, 3].TextString = insertTableDatas[row][2];
                    table.Cells[row + 2, 4].TextString = insertTableDatas[row][3];
                    //锁定
                    table.Cells[row + 2, 0].State = CellStates.ContentLocked;
                    table.Cells[row + 2, 1].State = CellStates.ContentLocked;
                    table.Cells[row + 2, 2].State = CellStates.ContentLocked;
                    table.Cells[row + 2, 3].State = CellStates.ContentLocked;
                    table.Cells[row + 2, 4].State = CellStates.ContentLocked;
                    //居中
                    table.Cells[row + 2, 0].Alignment = CellAlignment.MiddleCenter;
                    table.Cells[row + 2, 1].Alignment = CellAlignment.MiddleCenter;
                    table.Cells[row + 2, 2].Alignment = CellAlignment.MiddleCenter;
                    table.Cells[row + 2, 3].Alignment = CellAlignment.MiddleCenter;
                    table.Cells[row + 2, 4].Alignment = CellAlignment.MiddleCenter;

                }
                tableObjectid = table.ObjectId;
                table.GenerateLayout();
                long aa = table.Handle.Value; //句柄ID
                GValues.cadHandleId = aa.ToString();
                ResultBuffer rb = new ResultBuffer();
                rb.Add(new TypedValue((int)DxfCode.ExtendedDataRegAppName, "ACAD"));
                rb.Add(new TypedValue((int)DxfCode.ExtendedDataAsciiString, "productCode:" + GValues.productCode));
                rb.Add(new TypedValue((int)DxfCode.ExtendedDataAsciiString, "tableType:productBom"));
                table.XData = rb;
                //string bb = table.Handle.ToString();
                // 提交事务
                tr.Commit();
            }
            docLock.Dispose();
            ed.WriteMessage("已在指定位置插入表格。" + GValues.cadHandleId + "\n");
            WriteXDataByHandle(GValues.selectedBlockHandelId, "ACAD", GValues.cadHandleId, GValues.productCode); //tt1查询块里的BOM定义情况
        }

        private Point3d ConvertToWorldCoordinate(Point3d point, Editor ed)
        {
            // 正确的方法：使用Matrix3d进行坐标转换
            Matrix3d ucsToWcs = ed.CurrentUserCoordinateSystem;
            return point.TransformBy(ucsToWcs);
        }

        public void WriteXDataByHandle(string handle, string appName, string tableHandelId, string productCode)
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument();

            Editor ed = doc.Editor;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                try
                {
                    // 根据句柄查找对象
                    ObjectId objId = db.GetObjectId(false, new Handle(long.Parse(handle)), 0);
                    //if (!db.TryGetObjectId(new Handle(Convert.ToInt64(handle, 16)), out objId))
                    //{
                    //    ed.WriteMessage("\n无效的句柄");
                    //    return;
                    //}

                    // 验证是否为块参照
                    if (!objId.ObjectClass.IsDerivedFrom(RXObject.GetClass(typeof(BlockReference))))
                    {
                        ed.WriteMessage("\n该句柄不是块参照");
                        return;
                    }

                    BlockReference br = tr.GetObject(objId, OpenMode.ForWrite) as BlockReference;
                    // 创建XData
                    ResultBuffer xdata = new ResultBuffer(
                        new TypedValue((int)DxfCode.ExtendedDataRegAppName, appName),
                        new TypedValue((int)DxfCode.ExtendedDataAsciiString, "productCode:" + productCode),
                        new TypedValue((int)DxfCode.ExtendedDataAsciiString, "tableHandelId:" + tableHandelId),
                        new TypedValue((int)DxfCode.ExtendedDataAsciiString, "tableType:productBom"),
                        new TypedValue((int)DxfCode.ExtendedDataReal, DateTime.Now.ToOADate())
                    );

                    // 写入XData
                    br.XData = xdata;
                    ed.WriteMessage("\n成功写入XData到块：{}" + br.Name);
                    docLock.Dispose();
                    tr.Commit();
                }
                catch (Autodesk.AutoCAD.Runtime.Exception ex)
                {
                    ed.WriteMessage("\n操作失败：{}" + ex.Message);
                }
            }
        }
        public void FOB2TABLE(String processName, String processId)
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument();

            // 选择表格对象
            //PromptEntityOptions opts = new PromptEntityOptions("\n选择表格: ");
            //opts.SetRejectMessage("\n选择的不是表格对象.");
            //opts.AddAllowedClass(typeof(Table), true);
            //PromptEntityResult tableResult = ed.GetEntity(opts);

            if (PromptStatus.OK == PromptStatus.OK)
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    //Table table = tr.GetObject(tableResult.ObjectId, OpenMode.ForWrite) as Table;
                    ObjectId objectid = db.GetObjectId(false, new Handle(1), 0);
                    ObjectId[] ids = new ObjectId[] { objectid };
                    if (ids.Length > 0)
                    {
                        foreach (ObjectId id in ids)
                        {
                            Entity ent = id.GetObject(OpenMode.ForWrite) as Entity;
                            //Entity ent1 = tr.GetObject(id, OpenMode.ForRead) as Entity; 另外一种获取表格的方法
                            if (ent is Table)
                            {
                                Table table = ent as Table;
                                //解锁
                                for (int row = 0; row < (table.Rows.Count - 2); row++)
                                {
                                    table.Cells[row + 2, 0].State = CellStates.None;
                                    table.Cells[row + 2, 1].State = CellStates.None;
                                    table.Cells[row + 2, 2].State = CellStates.None;
                                    table.Cells[row + 2, 3].State = CellStates.None;
                                    table.Cells[row + 2, 4].State = CellStates.None;
                                }

                                for (int i = 2; i < table.Rows.Count; i++)
                                {
                                    table.Cells[i, 1].TextString = table.Cells[i, 1].TextString.Replace("*", "");
                                    if (table.Cells[i, 1].TextString == processName)
                                    {
                                        table.Cells[i, 1].TextString = table.Cells[i, 1].TextString + "*";
                                    }
                                }
                                //上锁
                                for (int row = 0; row < (table.Rows.Count - 2); row++)
                                {
                                    table.Cells[row + 2, 0].State = CellStates.ContentLocked;
                                    table.Cells[row + 2, 1].State = CellStates.ContentLocked;
                                    table.Cells[row + 2, 2].State = CellStates.ContentLocked;
                                    table.Cells[row + 2, 3].State = CellStates.ContentLocked;
                                    table.Cells[row + 2, 4].State = CellStates.ContentLocked;
                                }
                                table.GenerateLayout();
                                ResultBuffer rbXdata = new ResultBuffer();
                                ResultBuffer rb = new ResultBuffer(); ;
                                rb.Add(new TypedValue((int)DxfCode.ExtendedDataRegAppName, "ACAD"));
                                String XData_productCode = "";
                                foreach (TypedValue tv in rbXdata)
                                {
                                    switch ((DxfCode)tv.TypeCode)
                                    {
                                        case DxfCode.ExtendedDataRegAppName:
                                            //rb.Add(new TypedValue((int)DxfCode.ExtendedDataRegAppName, tv.ToString()));
                                            break;
                                        case DxfCode.ExtendedDataAsciiString:
                                            if (tv.ToString().IndexOf("processName:") == -1)
                                            {
                                                XData_productCode = tv.Value.ToString();
                                            }

                                            break;
                                        // 其他类型的DXF组码...
                                    }
                                }
                                rb.Add(new TypedValue((int)DxfCode.ExtendedDataAsciiString, XData_productCode));
                                rb.Add(new TypedValue((int)DxfCode.ExtendedDataAsciiString, "processName:" + processId));

                                table.XData = rb;
                            }
                        }
                    }

                    // 检查实体是否存在扩展数据
                    //if (table.XData != null)
                    //{
                    //    ResultBuffer rb = table.XData; // 获取实体的扩展数据

                    //    // 遍历ResultBuffer以查看数据
                    //    foreach (TypedValue tv in rb)
                    //    {
                    //        switch ((DxfCode)tv.TypeCode)
                    //        {
                    //            case DxfCode.ExtendedDataRegAppName:
                    //                regAppName = tv.ToString();
                    //                break;
                    //            case DxfCode.ExtendedDataAsciiString:
                    //                asciiData = tv.ToString();
                    //                break;
                    //            case DxfCode.ExtendedDataLayerName:
                    //                controlData = tv.ToString();
                    //                break;
                    //            // 其他类型的DXF组码...
                    //        }
                    //    }
                    //}
                    //else
                    //{
                    //    ed.WriteMessage("\n实体没有扩展数据！");
                    //}
                    ed.WriteMessage("\n设定当前工艺成功。 ");
                    tr.Commit();
                    docLock.Dispose();
                    // 刷新并保存
                    doc.Editor.UpdateScreen();
                    doc.Editor.Regen();
                }
            }
        }

        public void initTableDictData(Dictionary<String, Dictionary<String,String>> tableDict)
        {
            Dictionary<String,String> fieldDict = new Dictionary<string,string>();
            fieldDict["processBom"] = "false";
            fieldDict["productCode"] = "";
            fieldDict["tableHandleId"] = "";
            tableDict["processBom"] = fieldDict;

            fieldDict = new Dictionary<string, string>();
            fieldDict["oldTable"] = "false";
            fieldDict["productCode"] = "";
            fieldDict["tableHandleId"] = "";
            tableDict["oldTable"] = fieldDict;

            fieldDict = new Dictionary<string, string>();
            fieldDict["productBom"] = "false";
            fieldDict["productCode"] = "false";
            fieldDict["tableHandleId"] = "";
            tableDict["productBom"] = fieldDict;

            fieldDict = new Dictionary<string, string>();
            fieldDict["processSop"] = "false";
            fieldDict["processName"] = "";
            fieldDict["productCode"] = "";
            fieldDict["tableHandleId"] = "";
            tableDict["processSop"] = fieldDict;
        }
              
        public void SetInsertTable()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;

            // 获取点
            PromptPointOptions pointOptions = new PromptPointOptions("\n点击位置插入表格");
            PromptPointResult pointResult = ed.GetPoint(pointOptions);
            if (pointResult.Status != PromptStatus.OK)
                return;

            // 插入表格
            using (Transaction tr = doc.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)tr.GetObject(doc.Database.BlockTableId, OpenMode.ForRead);
                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

                Table table = new Table();
                table.SetSize(5, 3); // 行数和列数
                table.Position = pointResult.Value;

                btr.AppendEntity(table);
                tr.AddNewlyCreatedDBObject(table, true);

                tr.Commit();
            }

            ed.Regen();
        }
        public void initBomMaterialQty()
        {
            GValues.clickButtonText = "插入";
            //GValues.productCode = "";
            SetBomMaterialForm setObjectForm = new SetBomMaterialForm();
            //setObjectForm.Show();
            Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(null, setObjectForm);
            setObjectForm.initBomFormData();
        }


        public void SelectAndLabel(List<MrpProductBomMaterialProperty> propertys,Action<int,List<String>> callback)
        {
            int count = 0;
            
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            List<String> handleIds = new List<string>();
            DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument();
            PromptSelectionOptions pso = new PromptSelectionOptions();
            pso.MessageForAdding = "\n请选择图形";
            pso.MessageForRemoval = "\n请移除图形";
            PromptSelectionResult psr = ed.GetSelection(pso);
            List<String> pointCenters = new List<string>();
            if (psr.Status != PromptStatus.OK) {
                ed.WriteMessage("\n未选择任何对象。");
                callback.Invoke(0,new List<string>());
                return;
            }
            SelectionSet ss = psr.Value;
            ObjectId[] selectedIds = ss.GetObjectIds();
            
            using (Transaction tr = doc.TransactionManager.StartTransaction())
            {
                foreach (ObjectId id in selectedIds)
                {
                    Entity entity = tr.GetObject(id, OpenMode.ForWrite) as Entity;
                    if (entity != null)
                    {
                        if (entity is Circle)
                        {
                            Circle c = entity as Circle;
                            pointCenters.Add(c.Center.X.ToString() + "-" + c.Center.Y.ToString());
                            entity.Erase();
                        }
                        if (entity is Arc)
                        {
                            entity.Erase();
                        }
                    }
                }
                pointCenters =  pointCenters.Distinct().ToList();
                count = pointCenters.Count;
                foreach (String centerPoint in pointCenters)
                {
                    Point3d point3d = new Point3d(double.Parse( centerPoint.Split('-')[0]),double.Parse( centerPoint.Split('-')[1]),0);
                    DBText text = new DBText
                    {
                        TextString = propertys[0].label,
                        Position = new Point3d(point3d.X + 10, point3d.Y + 10, point3d.Z),
                        Height = 10, //设置文本高度
                        ColorIndex = getColorIndex(propertys[0].color.ToString())
                    };
                    
                    BlockTableRecord btr = tr.GetObject(doc.Database.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                    btr.AppendEntity(text);
                    tr.AddNewlyCreatedDBObject(text, true);
                    handleIds.Add(text.Handle.Value.ToString());
                    foreach (MrpProductBomMaterialProperty property in propertys)
                    {
                        Circle circle = new Circle();
                        circle = new Circle(point3d, Vector3d.ZAxis, double.Parse( property.redius));
                        //circle.Color = Color.FromRgb(255, 0,0);
                        circle.ColorIndex = getColorIndex(property.color);
                       
                        btr.AppendEntity(circle);
                        tr.AddNewlyCreatedDBObject(circle, true);
                        handleIds.Add(circle.Handle.Value.ToString());
                    }
                }

                //// 将圆添加到数据库中
                //acCurDbase.Add(circle);

                //// 刷新视图以显示新创建的圆
                //acEd.Regen(Regapp.kRedraw);
                tr.Commit();
                docLock.Dispose();
                doc.Editor.UpdateScreen();
                doc.Editor.Regen();
            }
            callback.Invoke(count,handleIds);
        }
        public void addSelectAndLabel(ProductBomTree productBomTree, List<String> handleIds,int count, Action<int, List<String>> callback)
        {
            // Get the current document and database
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument();
            Editor ed = doc.Editor;
            String productId = productBomTree.pid;
            String materialId = productBomTree.id;

            List<MrpProductBomMaterialProperty> propertys = productBomTree.materialProperties;
            List<String> pointCenters = new List<string>();
            if (handleIds != null && handleIds.Count > 0)
            {
                //List<ObjectId> objIds = new List<ObjectId>();
                // Convert the entered handle to an ObjectId
                //foreach (String handleId in handleIds)
                //{
                //    ObjectId objId = ObjectId.Null;
                //    try
                //    {
                //        objId = HostApplicationServices.WorkingDatabase.GetObjectId(false, new Handle(long.Parse(handleId)), 0); ;
                //        objIds.Add(objId);
                //    }
                //    catch (Autodesk.AutoCAD.Runtime.Exception ex)
                //    {
                //        ed.WriteMessage("\n不合法的handle: " + ex.Message);
                //        return;
                //    }
                //}
                // Create a selection set from the ObjectId
                //SelectionSet ss = SelectionSet.FromObjectIds(objIds.ToArray()); //根据已有Object ID 创建选择集合。
                // Add the selection set to the current selection set
                //ed.SetImpliedSelection(ss);
                //ed.WriteMessage("\n已经选择了的图形。");
                // Prompt the user to manually select other objects
                //doc.SendStringToExecute(" ", true, false, false);
                PromptSelectionOptions psoManual = new PromptSelectionOptions();
                psoManual.MessageForAdding = "\n请选择需要添加的图形 ";
                PromptSelectionResult psrManual = ed.GetSelection(psoManual);
                if (psrManual.Status != PromptStatus.OK)
                {
                    ed.WriteMessage("\n未选择任何对象。");
                    return;
                }
                // Add the manually selected objects to the selection set
                //ss = SelectionSet.FromObjectIds(ss.GetObjectIds().Concat(psrManual.Value.GetObjectIds()).ToArray());
                SelectionSet ss1 = psrManual.Value;
                //ed.SetImpliedSelection(ss);
                //ed.WriteMessage("\n继续选择图形。");
                // Open a transaction
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    ObjectId[] selectedIds = ss1.GetObjectIds();
                    foreach (ObjectId id in selectedIds)
                    {
                        Entity entity = tr.GetObject(id, OpenMode.ForWrite) as Entity;
                        if (entity != null)
                        {
                            if (entity is Circle)
                            {
                                Circle c = entity as Circle;
                                pointCenters.Add(c.Center.X.ToString() + "-" + c.Center.Y.ToString());
                                entity.Erase();
                            }
                            if (entity is Arc)
                            {
                                entity.Erase();
                            }
                        }
                    }
                    pointCenters = pointCenters.Distinct().ToList();
                    count = pointCenters.Count + count;
                    foreach (String centerPoint in pointCenters)
                    {
                        Point3d point3d = new Point3d(double.Parse(centerPoint.Split('-')[0]), double.Parse(centerPoint.Split('-')[1]), 0);
                        DBText text = new DBText
                        {
                            TextString = propertys[0].label,
                            Position = new Point3d(point3d.X + 10, point3d.Y + 10, point3d.Z),
                            Height = 10, //设置文本高度
                            ColorIndex = getColorIndex(propertys[0].color.ToString())
                        };

                        BlockTableRecord btr = tr.GetObject(doc.Database.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                        btr.AppendEntity(text);
                        tr.AddNewlyCreatedDBObject(text, true);
                        handleIds.Add(text.Handle.Value.ToString());
                        addXdata(text, productId, materialId);
                        foreach (MrpProductBomMaterialProperty property in propertys)
                        {
                            Circle circle = new Circle();
                            circle = new Circle(point3d, Vector3d.ZAxis, double.Parse(property.redius));
                            //circle.Color = Color.FromRgb(255, 0,0);
                            circle.ColorIndex = getColorIndex(property.color);

                            btr.AppendEntity(circle);
                            tr.AddNewlyCreatedDBObject(circle, true);
                            handleIds.Add(circle.Handle.Value.ToString());
                            addXdata(circle, productId, materialId);
                        }
                    }
                    // Commit the transaction
                    tr.Commit();
                    docLock.Dispose();
                    doc.Editor.UpdateScreen();
                    doc.Editor.Regen();
                }
            }
            callback.Invoke(count, handleIds);
        }
        public void cancelSelectAndLabel(ProductBomTree productBomTree, List<String> handleIds,int count, Action<int, List<String>> callback)
        {
            // Get the current document and database
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument();
            Editor ed = doc.Editor;
            List<MrpProductBomMaterialProperty> propertys = productBomTree.materialProperties;
            String productId = productBomTree.pid;
            String materialId = productBomTree.id;
            List<String> pointCenters = new List<string>();
            if (handleIds != null && handleIds.Count > 0)
            {
                ed.WriteMessage("\n请选择需要取消的图形:");
                //doc.SendStringToExecute(" ", true, false, false);
                // Prompt the user to manually select other objects
                PromptSelectionOptions psoManual = new PromptSelectionOptions();
                psoManual.MessageForAdding = "\n请选择需要取消的图形:";
                PromptSelectionResult psrManual = ed.GetSelection(psoManual);
                if (psrManual.Status != PromptStatus.OK)
                {
                    ed.WriteMessage("\n未选择任何对象。");
                    return;
                }
                // Add the manually selected objects to the selection set
                //ss = SelectionSet.FromObjectIds(ss.GetObjectIds().Concat(psrManual.Value.GetObjectIds()).ToArray());
                //ed.SetImpliedSelection(ss);
                //ed.WriteMessage("\n继续选择图形。");
                SelectionSet ss = psrManual.Value;
                ObjectId[] selectedIds = ss.GetObjectIds();
                // Open a transaction
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    foreach (ObjectId id in selectedIds)
                    {
                        Entity entity = tr.GetObject(id, OpenMode.ForWrite) as Entity;
                        if (entity != null && checkedXdata(entity,productId,materialId))
                        {
                            handleIds.RemoveAll(item => item.Contains(entity.Handle.Value.ToString()));
                            if (entity is Circle)
                            {
                                Circle c = entity as Circle;
                                c.ColorIndex = getColorIndex("white");
                                pointCenters.Add(c.Center.X.ToString() + "-" + c.Center.Y.ToString());
                            }
                            if (entity is DBText)
                            {
                                entity.Erase();
                            }
                            addXdata(entity, "none", "none");

                        }
                        else
                        {
                            ed.WriteMessage("\n没有物料数据！");
                        }
                    }
                    pointCenters = pointCenters.Distinct().ToList();
                    count = count - pointCenters.Count;
                    // Commit the transaction
                    tr.Commit();
                    docLock.Dispose();
                    doc.Editor.UpdateScreen();
                    doc.Editor.Regen();
                }
            }
            callback.Invoke(count, handleIds);
        }
        public void addXdata(Entity ent,String productCode,String materialCode)
        {
            ResultBuffer rb = new ResultBuffer(); ;
            rb.Add(new TypedValue((int)DxfCode.ExtendedDataRegAppName, "ACAD"));
            rb.Add(new TypedValue((int)DxfCode.ExtendedDataAsciiString, "materialCode:" + materialCode));
            rb.Add(new TypedValue((int)DxfCode.ExtendedDataAsciiString, "productCode:" + productCode));
            ent.XData = rb;
        }
        public bool checkedXdata(Entity ent, String productCode, String materialCode)
        {
            //ent.UpgradeOpen();
            //ent.Highlight();
            bool checkXdata = false;
            if (ent.XData != null)
            {
                ResultBuffer rb = ent.XData; // 获取实体的扩展数据

                // 遍历ResultBuffer以查看数据
                foreach (TypedValue tv in rb)
                {
                    switch ((DxfCode)tv.TypeCode)
                    {
                        case DxfCode.ExtendedDataRegAppName:
                            break;
                        case DxfCode.ExtendedDataAsciiString:
                            String data = tv.Value.ToString();
                            //if (data.IndexOf("productCode:") != -1)
                            //{
                            //    if (data.Split(':')[1] == productCode)
                            //    {
                            //        checkXdata = true;
                            //    }
                            //}
                            if (data.IndexOf("materialCode:") != -1)
                            {
                                if (data.Split(':')[1] == materialCode)
                                {
                                    checkXdata = true;
                                }
                            }
                            break;
                        // 其他类型的DXF组码...
                    }
                }
            }
            return checkXdata;
        }
        public void fromHandleIds(List<MrpProductBomMaterialProperty> propertys, List<String> handleIds, Action<int, List<String>> callback)
        {
            // Get the current document and database
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            // Prompt the user to enter a handle
            PromptStringOptions pso = new PromptStringOptions("\nEnter the handle of the object: ");
            PromptResult pr = ed.GetString(pso);

            if (pr.Status == PromptStatus.OK)
            {
                // Convert the entered handle to an ObjectId
                ObjectId objId = ObjectId.Null;
                try
                {
                    objId = HostApplicationServices.WorkingDatabase.GetObjectId(false, new Handle(long.Parse(pr.StringResult)), 0); ;
                }
                catch (Autodesk.AutoCAD.Runtime.Exception ex)
                {
                    ed.WriteMessage("\nInvalid handle: " + ex.Message);
                    return;
                }

                // Open a transaction
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    // Try to get the object
                    Entity ent = tr.GetObject(objId, OpenMode.ForRead) as Entity;
                    if (ent != null)
                    {
                        // Create a selection set from the ObjectId
                        SelectionSet ss = SelectionSet.FromObjectIds(new ObjectId[] { objId });

                        // Add the selection set to the current selection set
                        ed.SetImpliedSelection(ss);

                        ed.WriteMessage("\nObject added to the selection set.");

                        // Prompt the user to manually select other objects
                        PromptSelectionOptions psoManual = new PromptSelectionOptions();
                        psoManual.MessageForAdding = "\nSelect other objects: ";
                        PromptSelectionResult psrManual = ed.GetSelection(psoManual);

                        if (psrManual.Status == PromptStatus.OK)
                        {
                            // Add the manually selected objects to the selection set
                            ss = SelectionSet.FromObjectIds(ss.GetObjectIds().Concat(psrManual.Value.GetObjectIds()).ToArray());

                            ed.SetImpliedSelection(ss);

                            ed.WriteMessage("\nManually selected objects added to the selection set.");
                        }
                    }
                    else
                    {
                        ed.WriteMessage("\nCould not find the object with the specified handle.");
                    }

                    // Commit the transaction
                    tr.Commit();
                }
            }
        }

        public void GenerateAndInsertQRCode(string text, Point3d insertionPoint, double scale, int width = 200, int height = 200)
        {
            // 生成二维码
            Bitmap qrCodeImage = GenerateQRCode(text, width, height);

            // 保存二维码为临时文件
            string tempFilePath = Path.GetTempFileName() + ".png";
            qrCodeImage.Save(tempFilePath);

            // 将二维码插入到CAD中
            InsertQRCodeIntoCAD(tempFilePath, insertionPoint, scale);

            // 删除临时文件
            //File.Delete(tempFilePath);
        }
        public  RasterImageDef AddImageDef(Database db, Transaction trans, string imageFilespec)
        {
            if (!File.Exists(imageFilespec))
                throw new FileNotFoundException(imageFilespec);
            ObjectId idImageDict = RasterImageDef.GetImageDictionary(db);
            if (idImageDict.IsNull)
                idImageDict = RasterImageDef.CreateImageDictionary(db);
            if (idImageDict.IsNull)
                throw new InvalidOperationException("failed to get or create image dictionary");
            DBDictionary imageDictionary = trans.GetObject(idImageDict, OpenMode.ForRead) as DBDictionary;
            if (imageDictionary == null)
                throw new InvalidOperationException("Failed to open image dictionary");
            RasterImageDef imageDef = new RasterImageDef();
            try
            {
                imageDef.SourceFileName = imageFilespec;
                imageDef.Load();

                String name = RasterImageDef.SuggestName(imageDictionary, imageFilespec);

                imageDictionary.UpgradeOpen();
                ObjectId idEntry = imageDictionary.SetAt(name, imageDef);

                if (idEntry.IsNull)
                    throw new InvalidOperationException("Failed to add image definition to image dictionary");

                trans.AddNewlyCreatedDBObject(imageDef, true);

                return imageDef;

            }
            catch
            {
                imageDef.Dispose();
                throw;
            }

        }
        public void InsertQRCodeIntoCAD(string filePath, Point3d insertionPoint, double scale)
        {
            // 打开当前文档
            Document doc = Application.DocumentManager.MdiActiveDocument;
            DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument();
            Database db = doc.Database;
            using (Transaction trans = doc.TransactionManager.StartTransaction())
            {
                ObjectId idModel = SymbolUtilityServices.GetBlockModelSpaceId(doc.Database);
                BlockTableRecord ms = trans.GetObject(idModel, OpenMode.ForWrite) as BlockTableRecord;
                RasterImageDef imageDef = AddImageDef(doc.Database, trans, filePath);
                if (imageDef != null)
                {
                    RasterImage image = new RasterImage();
                    image.ImageDefId = imageDef.ObjectId;
                    ObjectId imageId = ms.AppendEntity(image);
                    if (imageId.IsNull)
                        throw new Autodesk.AutoCAD.Runtime.Exception(ErrorStatus.NullObjectId);
                    trans.AddNewlyCreatedDBObject(image, true);
                    RasterImage.EnableReactors(true);
                    image.AssociateRasterDef(imageDef);
                    Point3d origin = (Point3d)Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("VIEWCTR");
                    image.Orientation = new CoordinateSystem3d(insertionPoint, Vector3d.XAxis, Vector3d.YAxis);
                    double scaleFactor = 10.0;
                    // 设置RasterImage的缩放值
                    double scaleX = 12.0; // X方向的缩放值
                    double scaleY = 12.0; // Y方向的缩放值
                    double scaleZ = 1.0; // Z方向的缩放值（通常为1）
                    // 创建一个缩放矩阵
                    Matrix3d scaleMatrix = Matrix3d.Scaling(scaleX, insertionPoint) * Matrix3d.Scaling(scaleY, insertionPoint) * Matrix3d.Scaling(scaleZ, insertionPoint);
                    // 应用缩放矩阵
                    image.TransformBy(scaleMatrix);

                }
                trans.Commit();
            }
            docLock.Dispose();
            
            //// 开始事务
            //using (Transaction tr = db.TransactionManager.StartTransaction())
            //{
            //    // 获取块表
            //    BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

            //    // 获取模型空间块表记录
            //    BlockTableRecord btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

            //    // 创建光栅图像
            //    RasterImageDef imageDef = new RasterImageDef();
            //    imageDef.SourceFileName = filePath;
            //    imageDef.Load();

            //    // Create a new RasterImageReference
            //    // 创建光栅图像实体
            //    Point3d origin = (Point3d)Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("VIEWCTR");
            //    RasterImage image = new RasterImage();
            //    image.ImageDefId = imageDef.ObjectId;
            //    RasterImage.EnableReactors(true);
            //    image.AssociateRasterDef(imageDef);
            //    image.Orientation = new CoordinateSystem3d(origin, Vector3d.XAxis, Vector3d.YAxis); 
            //    //image.Scale = scale;
            //    // 设置RasterImage的缩放值
            //    double scaleX = 12.0; // X方向的缩放值
            //    double scaleY = 12.0; // Y方向的缩放值
            //    double scaleZ = 1.0; // Z方向的缩放值（通常为1）

            //    // 创建一个缩放矩阵
            //    Matrix3d scaleMatrix = Matrix3d.Scaling(scaleX, origin) * Matrix3d.Scaling(scaleY, origin) * Matrix3d.Scaling(scaleZ, origin);
            //    // 应用缩放矩阵
            //    image.TransformBy(scaleMatrix);

            //    // 将图像添加到模型空间
            //    btr.AppendEntity(image);
            //    tr.AddNewlyCreatedDBObject(image, true);

            //    // 提交事务
            //    tr.Commit();
            //}
        }

        public Bitmap GenerateQRCode(string text, int width, int height)
        {
            var barcodeWriter = new BarcodeWriter
            {
                Format = BarcodeFormat.QR_CODE,
                Options = new QrCodeEncodingOptions
                {
                    Width = width,
                    Height = height,
                    Margin = 1
                }
            };

            return barcodeWriter.Write(text);
        }

        //public void SelectByHandles()
        //{
        //    // 获取当前文档和编辑器
        //    Document doc = Application.DocumentManager.MdiActiveDocument;
        //    Editor editor = doc.Editor;

        //    // 提示用户输入多个Handle值，用逗号分隔
        //    PromptStringOptions pso = new PromptStringOptions("\n请输入对象的Handle值，多个Handle用逗号分隔：");
        //    PromptResult pr = editor.GetString(pso);
        //    if (pr.Status != PromptStatus.OK) return;

        //    // 将输入的Handle值分割为数组
        //    string[] handleStrings = pr.StringResult.Split(',');

        //    // 创建一个列表来存储有效的ObjectId
        //    List<ObjectId> objectIds = new List<ObjectId>();

        //    foreach (string handleString in handleStrings)
        //    {
        //        string trimmedHandle = handleString.Trim();
        //        if (string.IsNullOrEmpty(trimmedHandle)) continue;

        //        // 将Handle值转换为ObjectId
        //        Handle handle = new Handle(long.Parse(trimmedHandle));
        //        ObjectId objectId = HostApplicationServices.WorkingDatabase.GetObjectId(false, handle, 0);

        //        if (objectId != ObjectId.Null)
        //        {
        //            objectIds.Add(objectId);
        //        }
        //        else
        //        {
        //            editor.WriteMessage("\n未找到与Handle值 '{trimmedHandle}' 匹配的对象。");
        //        }
        //    }

        //    // 如果没有有效的ObjectId，提示用户并退出
        //    if (objectIds.Count == 0)
        //    {
        //        editor.WriteMessage("\n未找到任何有效的对象。");
        //        return;
        //    }

        //    // 创建一个选择集，包含通过Handle获取的对象
        //    PromptSelectionOptions pso2 = new PromptSelectionOptions();
        //    pso2.MessageForAdding = "\n请手工选择更多对象：";
        //    PromptSelectionResult psr = editor.GetSelection(pso2, new SelectedObject(objectIds.ToArray()));

        //    if (psr.Status == PromptStatus.OK)
        //    {
        //        // 获取最终的选择集
        //        SelectionSet finalSelectionSet = psr.Value;
        //        editor.WriteMessage("\n最终选择的对象总数：{finalSelectionSet.Count}");

        //        // 可以在这里对选择集中的对象进行操作
        //        using (Transaction tr = doc.Database.TransactionManager.StartTransaction())
        //        {
        //            foreach (SelectedObject so in finalSelectionSet)
        //            {
        //                Entity entity = tr.GetObject(so.ObjectId, OpenMode.ForRead) as Entity;
        //                editor.WriteMessage("\n选择的对象类型：{entity.GetType().Name}");
        //            }
        //            tr.Commit();
        //        }
        //    }
        //    else
        //    {
        //        editor.WriteMessage("\n未选择任何对象。");
        //    }
        //}
        
        private Polyline drawPloygon(Double x,Double y,Double radius)
        {
            Point2d center = new Point2d(x, y);
            int sideNum = 10;
            double startAngle = 0;
            Polyline polyline = new Polyline();
            for (int i = 0; i < sideNum; i++)
            {
                double angle = startAngle + i * (Math.PI * 2 / sideNum);
                Point2d vertex = new Point2d(center.X + radius * Math.Cos(angle), center.Y + radius * Math.Sin(angle));
                polyline.AddVertexAt(i, vertex, 0, 0, 0);
            }
            polyline.Closed = true;
            polyline.Color = Autodesk.AutoCAD.Colors.Color.FromRgb(255, 0,0);
            return polyline;                
        }
        private Point3d GetLabelPoint(Entity ent)
        {
            if (ent is Line)
            {
                Line line = ent as Line;
                return new Point3d(line.StartPoint.X, line.StartPoint.Y, 0);
            }
            else if (ent is Circle)
            {
                Circle circle = ent as Circle;
                return circle.Center;
            }
            else if (ent is Arc)
            {
                Arc arc = ent as Arc;
                return arc.Center;
            }
            else
            {
                return ent.GeometricExtents.MinPoint;//几何
            }

        }
        public void AddTextNearShape()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            // 选择图形
            PromptEntityOptions peo = new PromptEntityOptions("\n选择图形: ");
            peo.SetRejectMessage("\n选择的不是图形，请重新选择。");
            //peo.AddAllowedClass(typeof(BlockReference), true);//图片选择属性
            PromptEntityResult per = ed.GetEntity(peo);

            if (per.Status == PromptStatus.OK)
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    Entity entity = tr.GetObject(per.ObjectId, OpenMode.ForWrite) as Entity;

                    // 获取图形的位置
                    Point3d position = entity.GeometricExtents.MinPoint;

                    // 创建文本对象
                    DBText text = new DBText();
                    text.Position = new Point3d(position.X + 10, position.Y + 10, position.Z); // 在图形旁边的位置
                    text.TextString = "A";
                    text.Height = 10; // 设置文本高度

                    // 将文本添加到模型空间
                    BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                    BlockTableRecord btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                    btr.AppendEntity(text);
                    tr.AddNewlyCreatedDBObject(text, true);

                    tr.Commit();
                }
            }
        }

        public int getColorIndex(String colorName)
        {
            colorName = colorName.ToUpper();
            if (colorName == "RED")
            {
                return 1;
            }
            else if (colorName == "YELLOW")
            {
                return 2;
            }
            else if (colorName == "GREEN")
            {
                return 3;
            }
            else if (colorName == "CYAN") //青色
            {
                return 4;
            }
            else if (colorName == "BLUE")
            {
                return 5;
            }
            else if (colorName == "PURPLE") //紫色
            {
                return 6;
            }
            else if (colorName == "WHITE")
            {
                return 7;
            }
            else if (colorName == "GRAY") //灰色
            {
                return 8;
            }
            else 
            {
                return 1;
            }
        }



        //public void LabelSelectedEntities()
        //{
        //    // 获取当前文档和数据库
        //    Document doc = Application.DocumentManager.MdiActiveDocument;
        //    Database db = doc.Database;
        //    Editor ed = doc.Editor;

        //    // 启动选择集操作，允许用户进行窗口选择
        //    PromptSelectionResult selRes = ed.SelectWindow();
        //    if (selRes.Status != PromptStatus.OK) return; // 用户取消选择

        //    // 获取选中的对象集合
        //    SelectionSet selSet = selRes.Value;
        //    using (Transaction trans = db.TransactionManager.StartTransaction())
        //    {
        //        foreach (ObjectId objId in selSet)
        //        {
        //            Entity ent = trans.GetObject(objId, OpenMode.ForWrite) as Entity;
        //            if (ent != null)
        //            {
        //                // 在每个实体旁边添加文本标识A
        //                DBText text = new DBText();
        //                text.TextString = "A"; // 设置文本内容为A
        //                text.Position = ent.GeometricExtents.GetMaxPoint(); // 将文本放置在实体的右上角
        //                text.Position = new Point3d(text.Position.X + 1, text.Position.Y + 1, 0); // 稍微偏移一点位置以便显示
        //                text.Height = 0.25; // 设置文本高度
        //                db.AddObjectToTransaction(text); // 将文本添加到事务中
        //            }
        //        }
        //        trans.Commit(); // 提交事务，使更改生效
        //    }
        //}
                //PromptPointOptions ppo = new PromptPointOptions("\nSelect first corner of plot area: ");
                //ppo.AllowNone = false;
                //PromptPointResult ppr = ed.GetPoint(ppo);
                //if (ppr.Status != PromptStatus.OK)
                //    return;
                //Point3d first1 = ppr.Value;
                //PromptCornerOptions pco = new PromptCornerOptions("\nSelect second corner of plot area: ", first1);
                //ppr = ed.GetCorner(pco);
                //if (ppr.Status != PromptStatus.OK)
                //    return;
                //Point3d second2 = ppr.Value;

        //public void SelectAndLabelShapes()
        //{
        //    Document doc = Application.DocumentManager.MdiActiveDocument;
        //    Database db = doc.Database;
        //    Editor ed = doc.Editor;

        //    // 提示用户选择窗口的第一个角点
        //    PromptPointResult ppr1 = ed.GetPoint("\n选择窗口的第一个角点: ");
        //    if (ppr1.Status != PromptStatus.OK)
        //        return;

        //    // 提示用户选择窗口的对角点
        //    PromptCornerOptions pco = new PromptCornerOptions("\n选择窗口的对角点: ");
        //    pco.Keywords.Add("C", "Crossing", "交叉窗口");
        //    pco.Keywords.Add("W", "Window", "窗口");
        //    pco.Keywords.Default = "W";
        //    pco.AllowNone = true;
        //    pco.UseBasePoint = true;
        //    pco.BasePoint = ppr1.Value;
        //    PromptPointResult ppr2 = ed.GetCorner(pco);
        //    if (ppr2.Status != PromptStatus.OK)
        //        return;

        //    // 根据用户选择的窗口类型创建选择集
        //    SelectionFilter sf = new SelectionFilter(new TypedValue[] { new TypedValue((int)DxfCode.Start, "CIRCLE,LINE,ARC") });
        //    PromptSelectionResult psr = ed.SelectCrossingWindow(ppr1.Value, ppr2.Value, sf);
        //    if (psr.Status != PromptStatus.OK)
        //        return;

        //    // 遍历选择集并在选中的图形旁边添加字母A
        //    using (Transaction tr = db.TransactionManager.StartTransaction())
        //    {
        //        SelectionSet ss = psr.Value;
        //        ed.WriteMessage("\n选中了 {0} 个对象:", ss.Count);
        //        foreach (SelectedObject so in ss)
        //        {
        //            Entity ent = tr.GetObject(so.ObjectId, OpenMode.ForWrite) as Entity;
        //            Point3d position = ent.GeometricExtents.MinPoint;

        //            // 创建文本对象
        //            DBText text = new DBText();
        //            text.Position = new Point3d(position.X + 10, position.Y + 10, position.Z); // 在图形旁边的位置
        //            text.TextString = "A";
        //            text.Height = 10; // 设置文本高度

        //            // 将文本添加到模型空间
        //            BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
        //            BlockTableRecord btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
        //            btr.AppendEntity(text);
        //            tr.AddNewlyCreatedDBObject(text, true);

        //            ed.WriteMessage("\n在 {0} 旁边添加了字母A", ent.GetType().Name);
        //        }
        //        tr.Commit();
        //    }
        //}
    
    }
}
